<!-- 基础设置--部门信息--公司弹框-->
<template>
  <a-modal v-model:visible="visible" :title="title" :width="700">
    <!-- <a-alert>
      关闭弹窗后，上传信息不会中断，返回窗口后，上传不会中断。在下载悬浮窗显示上传信息
    </a-alert> -->
    <a-form
      :rules="rules"
      ref="refForm"
      :model="formData"
      label-align="right"
      auto-label-width
      class="UploadForm"
    >
      <a-form-item
        field="fileBelongId"
        label="指定文件夹:"
        required
        :rules="[
          {
            required: true,
            message: '指定文件夹是必选项！'
          }
        ]"
      >
        <a-cascader
          :field-names="fieldNames"
          :options="TreeData"
          v-model="formData.fileBelongId"
          check-strictly
          :path-mode="true"
          placeholder="请选择文件夹"
        />
      </a-form-item>
      <a-form-item field="storeName" label="本地上传:">
        <div>
          <a-button type="outline" @click="choiceFile"> 选择文件 </a-button>
          <div class="UploadForm-tip">
            支持mp4格式，单个视频大小超过5GB:一次最多上传10个文件，当前最大支持720高清转码
          </div>
        </div>
      </a-form-item>
    </a-form>
    <a-table :data="getFileTable" :pagination="false">
      <template #columns>
        <a-table-column title="文件名" :width="200">
          <template #cell="{ record }">
            <a-typography-paragraph
              :ellipsis="{
                rows: 1
              }"
            >
              {{ record.useFileName }}
            </a-typography-paragraph>
          </template>
        </a-table-column>
        <a-table-column title="大小" :width="100">
          <template #cell="{ record }">
            {{ (record.size / 1024 / 1024).toFixed(2) }}MB
          </template>
        </a-table-column>
        <a-table-column title="进度" :width="200">
          <template #cell="{ record }">
            <a-progress
              :percent="Number((record.fileStart / record.size).toFixed(4))"
            />
          </template>
        </a-table-column>
        <a-table-column title="设置" :width="150">
          <template #cell="{ record }">
            <a-link
              v-if="record.state === 'run'"
              status="warning"
              @click="uploadFileStore.edItUploadState(record.uuid, 'stop')"
            >
              停止上传
            </a-link>
            <a-link
              v-else-if="record.state !== 'success'"
              @click="startUploadFile(record)"
            >
              开始上传
            </a-link>
            <a-link
              status="danger"
              @click="uploadFileStore.delUpLoadList(record.uuid)"
            >
              删除
            </a-link>
          </template>
        </a-table-column>
      </template>
    </a-table>
    <template #footer>
      <a-button @click="handleCancel">隐藏</a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { useUploadFileStore } from '@/store/index';
import {
  openChoiceFile,
  imgTypeList,
  officeTypeList,
  vidoeTypeList,
  audioTypeList
} from '@/utils/file';
import {
  PostStorageDisk,
  getFileDelong,
  getPubliceFileBelong,
  FileUploadVerification
} from '@/apis/document/documentCenter/index';

function treeToArray(tree) {
  return tree.reduce((res, item) => {
    const { children, ...i } = item;
    return res.concat(
      i,
      children && children.length ? treeToArray(children) : []
    );
  }, []);
}

const formData = reactive<any>({ fileBelongId: undefined });
const tenants = JSON.parse(localStorage.getItem('tenants') as any);
const fieldNames = { value: 'id', label: 'storeName' };
const props = withDefaults(
  defineProps<{
    fileTypeId?: number;
    title?: string;
    userId: number;
  }>(),
  {
    title: '上传文件'
  }
);
const uploadFileStore = useUploadFileStore();
const userId = Number(localStorage.getItem('userId'));
const emit = defineEmits(['hide']);
const getFileTable = computed(() => {
  return uploadFileStore.uploadFileList.filter(
    (ele) => ele.fileAttribute === 1
  );
});
// watch(
//   () => props.fileTypeId,
//   () => {
//     fileBelongId.value = props.fileTypeId;
//   }
// );

// const choiceFile = async () => {
//   const [file] = await openChoiceFile(
//     [...imgTypeList, ...officeTypeList, ...vidoeTypeList, ...audioTypeList],
//     1,
//     0
//   );
//   const newAddr = treeToArray(props.tree);
//   let route = `/${userId}`;
//   newAddr.forEach((item: any) => {
//     if (fileBelongId.value.findIndex((ele) => ele === item.id) > -1) {
//       route = `${route}/${item.storeName}`;
//     }
//   });
//   console.log(
//     route,
//     fileBelongId.value[fileBelongId.value.length - 1],
//     fileBelongId.value,
//     newAddr
//   );
//   uploadFileStore.addUpLoadList(
//     file,
//     fileBelongId.value[fileBelongId.value.length - 1],
//     route,
//     userId
//   );
// };
const TreeData = ref([]);
const getData = async () => {
  const res = await getPubliceFileBelong();
  TreeData.value = [res];
};

const choiceFile = async () => {
  const [file] = await openChoiceFile(
    [...imgTypeList, ...officeTypeList, ...vidoeTypeList, ...audioTypeList],
    1,
    0
  );
  const newAddr = treeToArray(TreeData.value);
  const fileBelongIdValue = formData.fileBelongId;
  let route = tenants[0].clientName;
  newAddr.forEach((item: any) => {
    if (fileBelongIdValue.findIndex((ele) => ele === item.id) > -1) {
      route += `/${item.storeName}`;
    }
  });
  console.log(
    route,
    formData.fileBelongId[formData.fileBelongId.length - 1],
    formData.fileBelongId,
    newAddr
  );
  const { addUpLoadList } = uploadFileStore;
  const lastBelongId = fileBelongIdValue[fileBelongIdValue.length - 1];
  addUpLoadList(file, lastBelongId, route, userId, 1);
};

const refForm = ref();
const visible = ref(false);
defineExpose({ visible });

const startUploadFile = async (record: any) => {
  const { fileBelongId, fileAttribute, size, userId } = record;
  const res = await FileUploadVerification({
    fileBelongId,
    fileAttribute,
    fileSize: size,
    userId
  });
  if (res === '通过检验') uploadFileStore.edItUploadState(record.uuid, 'run');
};

const handleCancel = () => {
  visible.value = false;
  emit('hide', true);
};

// // //加载树
// const treeData = ref<any[]>([
//   {
//     value: 'beijing',
//     label: 'Beijing',
//     children: [
//       {
//         value: 'chaoyang',
//         label: 'ChaoYang',
//         children: [
//           {
//             value: 'datunli',
//             label: 'Datunli'
//           }
//         ]
//       },
//       {
//         value: 'haidian',
//         label: 'Haidian'
//       },
//       {
//         value: 'dongcheng',
//         label: 'Dongcheng'
//       },
//       {
//         value: 'xicheng',
//         label: 'Xicheng',
//         children: [
//           {
//             value: 'jinrongjie',
//             label: 'Jinrongjie'
//           },
//           {
//             value: 'tianqiao',
//             label: 'Tianqiao'
//           }
//         ]
//       }
//     ]
//   },
//   {
//     value: 'shanghai',
//     label: 'Shanghai',
//     children: [
//       {
//         value: 'huangpu',
//         label: 'Huangpu'
//       }
//     ]
//   }
// ]);
// const loadTree = async () => {
//   const { children } = await GetFileStoreTree();
//   children
//     ? [{ id: 0, storeName: '默认分类' }, ...children]
//     : [{ id: 0, storeName: '默认分类' }];
// };

watch(visible, (res) => {
  if (res) getData();
});

const rules = {};
</script>

<style scoped lang="less">
.UploadForm {
  margin-top: 20px;
  width: 400px;
  &-tip {
    margin-top: 10px;
    color: var(--color-neutral-6);
    font-size: 12px;
  }
}
</style>
